package com.css.zfzx.fwsjcj.modules.login.controller;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.config.property.PlatformConfig;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.org.online.session.SingleLogin;
import com.css.bpm.platform.page.login.controller.captcha.CaptchaService;
import com.css.bpm.platform.page.login.repository.entity.LoginSuccessLogEntity;
import com.css.bpm.platform.page.login.security.LoginSecretPool;
import com.css.bpm.platform.page.login.service.LoginService;
import com.css.bpm.platform.page.login.viewobjects.PwdCheck;
import com.css.bpm.platform.sys.pwdconfig.service.SysPwdConfigService;
import com.css.bpm.platform.sys.sysconfig.repository.entity.SysConfigEntity;
import com.css.bpm.platform.sys.sysconfig.service.SysConfigService;
import com.css.bpm.platform.sys.syssubapp.repository.entity.SysSubappEntity;
import com.css.bpm.platform.sys.syssubapp.service.SysSubappService;
import com.css.bpm.platform.utils.PlatformHttpRequestUtils;
import com.css.bpm.platform.utils.PlatformJwtUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformRSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dc
 * @date 2020-05-20
 * @since 1.0.0
 */

@RestController
@RequestMapping("/fw")
@Slf4j
public class FwLoginController {

    @Autowired
    SysConfigService sysConfigService;
   /* @Autowired
    LoginService loginService;*/
    @Autowired
    CaptchaService captchaService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    PlatformConfig platFormConfig;

    private static final String SESSION_RSAMAP_KEY = "PLATFORM_RSAMAP";
    private static final String PUBLIC_KEY = "PUBLIC_KEY";
    private static final String SESSION_ISCAPTCHA_KEY = "PLATFORM_ISCAPTCHA";
    @Autowired
    PlatformConfig platformConfig;

    @Autowired
    SysPwdConfigService sysPwdConfigService;

    @Autowired
    SysSubappService sysSubappService;


    @GetMapping("/login")
    public String login(HttpServletRequest request, Model model) throws Exception {
        Map<String, String> keyMap = LoginSecretPool.getKeys();
        request.getSession().setAttribute(SESSION_RSAMAP_KEY, keyMap);
        model.addAttribute(PUBLIC_KEY, keyMap.get(PlatformRSAUtils.PUBLIC_KEY));
        Boolean isCaptcha = platformConfig.getIsCaptcha();
        model.addAttribute(SESSION_ISCAPTCHA_KEY, isCaptcha);
        SysConfigEntity config = sysConfigService.getSysConfig();
        model.addAttribute("title", config.getSystemName());
        model.addAttribute("logo", config.getLogo());
        model.addAttribute("copyright", config.getCopyright());
        return platformConfig.getLoginUrl();
    }


    @PostMapping("app/{userCode}/login")
    public RestResponse loginIn(HttpServletRequest request, @PathVariable("userCode") String userCode, @RequestBody Map<String, String> body) {

        RestResponse restResponse = null;
        String cipher = body.get("cipher");
        String appCode = body.get("appCode");
        String ios = request.getHeader("ios");
        if (PlatformObjectUtils.isEmpty(cipher)) {
            restResponse = RestResponse.fail("密码不能为空!");
            return restResponse;
        } else if (PlatformObjectUtils.isEmpty(appCode)) {
            restResponse = RestResponse.fail("系统编码不能为空!");
            return restResponse;
        } else {
            try {

                log.info("开始执行checkLoginPassword，userCode={},cipher={},appCode={}", new Object[]{userCode, cipher, appCode});
                SysSubappEntity subapp = sysSubappService.findByCode(appCode);
                if (PlatformObjectUtils.isNotEmpty(subapp)) {
                    String privateKey = null;
                    if ("1".equals(ios)) {
                        privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMfWwCmZe2rPLd8q" +
                                "2GT1cGqOkV4LUv+Xzw4peuMENkYSQrmevmPMz7p0RszW90cWZ1WCZVcz6MbZWS/j" +
                                "keILkZNnjRJRncWSZiqWwDs0QAJdWYFYRQ2oqKDazVzlWirEcXbhXmIlrETCYfvA" +
                                "eWkMNMmQgAMTJkuXeH/sg1v6Fe//AgMBAAECgYEAvG22hcMNxzmRFEOPBSsUk7TY" +
                                "RufAm/Ylq0HbeGFJV6ryNZoEBZBiMnpfI9hyExqB1vP74Ey26YCZgvk+XfjwinVm" +
                                "ieaAnGLmyFbOsQxV84Sa5MAtDfoOj1Za9CzXPaEXsK3HxE8zwuDgJ020oNstC87l" +
                                "gWybYaVt7nuX4zRAr/ECQQDi/7e5FMfYyASYKrcKVv+GBGC+sQoAgaQHX+3kUgUp" +
                                "1yRXzc+2VrwxOd0Wqg8XrnM5wtbAtDyYaujpQcaGUZd5AkEA4V66+N44TzcWtrDk" +
                                "W5gN8gwbKhPRHoUyH1me8c45thrmuZobs0MdU181hPPPKX+NMWUkl1xUM44/M4R4" +
                                "ETdNNwJASl5a87ECNFx7XNsJssKD3oVKqM7ZpwbSFXRxPM8+T9HjXzzXYzaRW1NI" +
                                "wqceYLTPnUnfD608+PZ1rg3Vm6XZiQJBAKcwSXBaGlfZvEXnUGEKmj3X8Ubz0Izd" +
                                "ruNG7vzfSjzoFAXYZ3hC77xrwx5QaHyWnT3plI2c9vIQMp6bRR8wcV0CQGUCQz/2" +
                                "nSNMnHcn7Mqf8Cm/68bWFUK3e25frALjH447Uzp5xaJ4bu9kO0vHEpUs59q/5POk" +
                                "xqI6dh1UV2nWoTs=";
                    } else {
                        privateKey = subapp.getPrivateKey();
                    }
                    PwdCheck pwdCheck = PlatformAPI.getOrgAPI().getUserAPI().checkLoginPassword(userCode, cipher, privateKey);
                    if (pwdCheck.isSuccess()) {
                        pwdCheck.setToken(PlatformJwtUtils.createToken(subapp.getAppId()));
                        //onLoginSuccess(request, pwdCheck.getUserId());
                        HttpSession session = request.getSession();
                        session.setAttribute(PlatformConstants.CUR_USER_ID_IN_SESSION, pwdCheck.getUserId());
                    }
                    restResponse = RestResponse.succeed(pwdCheck);
                    log.info("结束执行checkLoginPassword，pwdCheck={}", pwdCheck);
                } else {
                    restResponse = RestResponse.fail("用户名或密码错误，appCode无效!");
                    log.info("结束执行checkLoginPassword，appCode无效");
                }

            } catch (Exception e) {
                log.error("用户名或密码错误!", e);
                restResponse = RestResponse.fail("用户名或密码错误!");
            }

            return restResponse;
        }

    }


   /* private void onLoginSuccess(HttpServletRequest request, String userId) {
        HttpSession session = request.getSession();
        session.setAttribute(PlatformConstants.CUR_USER_ID_IN_SESSION, userId);
        //TODO CSRF先不做
//        session.setAttribute(PlatformConstants.CSRFToken, UUIDGenerator.getUUID());
        String clientIp = PlatformHttpRequestUtils.getClientIp(request);
        try {
            if (platFormConfig.getIsCacheEnable()) {
                //从session中拿到用户id
                String userIdInSession = (String) session.getAttribute(PlatformConstants.CUR_USER_ID_IN_SESSION);
                if (userIdInSession != null) {
                    Map<String, String> map = redisTemplate.opsForHash().entries(PlatformConstants.MAP_ONLINE_USER);
                    if (PlatformObjectUtils.isEmpty(map)) {
                        map = new HashMap<String, String>();
                    }
                    map.put(userIdInSession, session.getId());
                    //TODO 调用单一登录
                    //SingleLogin.singleLogin(request);

                    SingleLogin.sessionInfo.put(userIdInSession, session);
                    redisTemplate.opsForHash().putAll(PlatformConstants.MAP_ONLINE_USER, map);
                }
            }
            LoginSuccessLogEntity logEntity = loginService.loginSuccessLog(userId, clientIp);
            session.setAttribute(PlatformConstants.LOGIN_SUCCESS_LOG_ID, logEntity.getId());
        } catch (Exception e) {
            log.error("记录登录成功日志失败！", e);
        }
    }*/


}
